package com.ruoyi.goods.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.Address;
import com.ruoyi.system.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Address)表控制层
 *
 * @author makejava
 * @since 2020-11-18 13:59:26
 */
@RestController
@RequestMapping("/address")
public class AddressController {
    /**
     * 服务对象
     */
    @Resource
    private AddressService addressService;
    @Autowired
    private TokenService tokenService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/info")
    public Address selectOne(Integer id) {
        return this.addressService.queryById(id);
    }

    /**
     * 获取用户的默认地址
     */
    @GetMapping("/default/info")
    public AjaxResult getDefault() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Address address = addressService.getDefault(Integer.parseInt(loginUser.getUser().getUserId().toString()));
        return AjaxResult.success(address);
    }

    /**
     * 所有用户地址的
     */
    @GetMapping("/info/list")
    public AjaxResult getList() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        List<Address> addresses = addressService.queryAllByLimit(loginUser.getUser().getUserId().toString());
        return AjaxResult.success(addresses);
    }

    /**
     * 修改用户地址信息通过地址Id
     */
    @PutMapping("/info")
    public AjaxResult updateInfo(@RequestBody Address address) {
        addressService.update(address);
        return AjaxResult.success();
    }

    /**
     * 添加地址
     *
     * @param address 地址信息
     */
    @PostMapping("/info")
    public AjaxResult addAddress(@RequestBody Address address) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userId = loginUser.getUser().getUserId().toString();
        if (address.getDefalut() == 1) {
            Address aDefault = addressService.getDefault(Integer.parseInt(userId));
            if (aDefault != null) {
                return AjaxResult.error("已经有默认地址不可重复添加");
            }
        }
        address.setUserId(userId);
        addressService.insert(address);
        return AjaxResult.success();
    }

    @DeleteMapping("/info")
    public AjaxResult deleteAddress(int id) {
        addressService.deleteById(id);
        return AjaxResult.success();
    }
}
